from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()


class Log(models.Model):
    LEVEL_CHOICES = [
        ('DEBUG', '调试'),
        ('INFO', '信息'),
        ('WARNING', '警告'),
        ('ERROR', '错误'),
    ]
    
    SOURCE_CHOICES = [
        ('SYSTEM', '系统'),
        ('PROJECT', '项目'),
        ('CASE', '测试用例'),
        ('SUITE', '测试套件'),
        ('USER', '用户操作'),
    ]
    
    timestamp = models.DateTimeField(auto_now_add=True, verbose_name='时间戳')
    level = models.CharField(max_length=10, choices=LEVEL_CHOICES, verbose_name='日志级别')
    source = models.CharField(max_length=20, choices=SOURCE_CHOICES, verbose_name='来源')
    message = models.TextField(verbose_name='消息内容')
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='用户')
    details = models.JSONField(default=dict, blank=True, verbose_name='详细信息')
    
    class Meta:
        db_table = 'logs_log'
        verbose_name = '日志'
        verbose_name_plural = '日志'
        ordering = ['-timestamp']
    
    def __str__(self):
        return f"[{self.level}] {self.source} - {self.message[:50]}"